// Copyright 2008 Google Inc.
// All Rights Reserved.

var FS = {};

osapps.mixin(FS, osapps.Loader);
osapps.mixin(FS, osapps.ui.Render);
osapps.mixin(FS, osapps.model.IApp);
if ((typeof gadgets == "object") && gadgets.Prefs) {
    FS.pref = new gadgets.Prefs();
}
FS.dynamicLoading.DEFAULT.JS.push("templates.js?12");
FS.dynamicLoading.DEFAULT.JS.push("requests.js?1");

FS.dynamicLoading.DEFAULT.CSS.push("style-xiaonei.css?3");

FS.PersonData = {};

//common utility functions

FS.alert = function(data){
    alert(gadgets.json.stringify(data));
};

FS.getMsg = function(messageid){
	if (FS.pref) {
              return FS.pref.getMsg(messageid);
        } else {
              return "MSG:{" + messageid + "}";
        }
}

FS.formatTime = function(ltime){
	var t = new Date(ltime);
	var str = [t.getFullYear(),"-",t.getMonth()+1,"-",t.getDate()," ",t.getHours(),":",t.getMinutes(),":",t.getSeconds()].join("");
	
	return str;
};

FS.isViewingSelf = function(){
	if (FS.owner && FS.owner.data && FS.viewer.data) {
		return FS.owner.data.userId === FS.viewer.data.userId;
	}else{
		return true;
	}
};

FS.subscribe(osapps.model.NotificationType.ALL_UPDATED, FS.refreshUI);

FS.start = function(){
    FS.getViewerProfile();
};

//This function is called when the gadget is shown.
FS.getViewerProfile = function(){
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), "viewer");
	var params = {
		"max" : 500
	};
    req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS,params), "viewer_friends");
    req.send(FS.onGetViewerProfileReturned);
};
FS.onGetViewerProfileReturned = function(dataResponse){
    FS.viewer = FS.viewer || {};
    FS.viewer.person = dataResponse.get("viewer").getData();
    var friends = dataResponse.get("viewer_friends").getData();
    FS.friendids = [];
    FS.viewer.friends = FS.viewer.friends || {};
    if (friends) {
        friends.each(function(person){
            FS.friendids.push(person.getId());
            FS.viewer.friends[person.getId()] = person;
        });
        
    }
    
    if (!FS.viewer.person) {
        alert("Failed to get profile from container: " + dataResponse.errors);
        return;
    }
    //  if(!FS.viewer.person.isOwner()) {
    //    alert("Cannot play this game in other's page.");
    //    return;
    //  }
    osapps.req.Request_DefaultHttpParameters["vid"] = FS.viewer.person.getId();
    osapps.req.Request_DefaultHttpParameters["oid"] = FS.viewer.person.getId();
    
	FS.showHome();
};

//when user click on friend link, browse that friend's profile
FS.showUserProfile = function(ownerId){
    FS.setDisplayingPage("Home");
    var req = new FS.req.GetPlayer(ownerId);
    FS.tempid = ownerId;
    req.send(FS.onShowUserProfileReturned);
    
};

//when the data returned from server.
FS.onShowUserProfileReturned = function(dataResponse){
    FS.owner = {};
	//TODO:need refactor return struct?
	FS.owner.person = {};
	FS.owner.person.getId = function(){
		return FS.tempid;
	};
    
    FS.stuffPersonData(dataResponse,FS.owner);
    FS.broadcast();
};

//when user click on friend link, browse that friend's profile
FS.showHome = function(){
	FS.setDisplayingPage("Home");
    var req = new FS.req.GetPlayer();
    req.send(FS.onShowHomeReturned);
};

FS.stuffPersonData = function(dataResponse,person){
	if(person == null) person = FS.viewer;
	var persondata = FS.extractResponse(dataResponse);
	person.data = persondata[person.person.getId()];
	FS.PersonData[person.person.getId()] = person.data;
	person.data.slaves = persondata.slaves;
	person.data.activities = persondata.activities;
		
	if (person.data.slaves) {
		for (var i = 0; i < person.data.slaves.length; i++) {
			var slavedata = person.data.slaves[i];
			FS.PersonData[slavedata.userId] = slavedata;
		}
	}
	
//	if (person.data.activities ) {
//		for (var i = 0; i < person.data.activities.length; i++) {
//			var activity = person.data.activities[i];
			//activity.text = FS.renderActivity(activity);
//		}
//	}
};
FS.onShowHomeReturned = function(response){
	if(!response.data.hasError){
		FS.stuffPersonData(response,FS.viewer);
    	FS.owner = FS.viewer;
    	FS.broadcast();
	}else{
		var name = FS.viewer.person.getDisplayName();
        var photoUrl = FS.viewer.person.getField(opensocial.Person.Field.THUMBNAIL_URL);
        var req = new FS.req.CreatePlayer(name, photoUrl);
        req.send(function(response){
			FS.stuffPersonData(response,FS.viewer);
			FS.owner = FS.viewer;
    		FS.broadcast();
			});
	}	
	
};

FS.showRank = function(){
	FS.setDisplayingPage("Rank");
    var req = new FS.req.FriendList();
    req.send(FS.onShowRankReturned);
};
FS.stuffFriendData = function(response){
	//TODO : onerror process
	var persondata = response.data;
	if (!persondata.hasError) {
        for (var p in persondata.data) {
            FS.PersonData[p] = persondata.data[p];
        }
    }
};
FS.onShowRankReturned = function(response){
    FS.stuffFriendData(response);
    FS.broadcast();
};

FS.showHelp = function(){
    FS.setDisplayingPage("Help");
    FS.onShowHelpReturned();
};

FS.onShowHelpReturned = function(){
    FS.broadcast();
};

FS.buySlave = function(){
    var req = new FS.req.Buy(FS.target.userId);
    req.send(function(response){
        FS.showReturnedMessage(response);
		FS.refreshCurrentPage();
		FS.newActivityFromResponse(response);
    });
};

FS.showReturnedMessage = function(response){
    FS.closeDialog();
    var message = FS.extractResponse(response);
	//FS.msgBox(FS.renderMessage(message),callback); in debug
    alert(FS.renderMessage(message));
};

FS.freeSlave = function(){
    var req = new FS.req.FreeSlave(FS.target.userId);
    req.send(function(response){
        FS.showReturnedMessage(response);
        FS.refreshCurrentPage();
		FS.newActivityFromResponse(response);
    });
};

FS.DostuffDialog = function(type, targetid){
    FS.target = FS.PersonData[targetid];
	FS.tempid = targetid;
    var req = new FS.req.CmdList(type);
    req.send(function(response){
        FS.Options = FS.extractResponse(response);
        FS.showDialog(type + 'Dialog');
    });
    
};

FS.Dostuff = function(){
    var stuff = document.getElementsByName("stuffid");
    var stuffid = null;
    if (stuff.length) {
        for (var i = 0; i < stuff.length; i++) {
            if (stuff[i].checked) {
                stuffid = stuff[i].value;
                break;
            }
        }
    } else {
        stuffid = document.getElementById("stuffid").value;
    }
    if (stuffid == null) {
        alert("select a stuff");
    }
    else {
        var req = new FS.req.Dostuff(stuffid, FS.tempid);
        req.send(function(response){
            FS.showReturnedMessage(response);
			
			if(!response.data.hasError){
				FS.refreshCurrentPage();
				FS.newActivityFromResponse(response);
			}
			
        });
    }
};

FS.Ransom = function(){
	var req = new FS.req.Ransom();
	req.send(function(response){
		FS.showReturnedMessage(response);
		FS.refreshCurrentPage();
		FS.newActivityFromResponse(response);
	});
}

FS.refreshCurrentPage = function(){
	if(FS.displayingPage == "Home"){
		FS.showHome();
	}else if(FS.displayingPage == "Rank"){
		FS.showRank();
	}else{
		FS.showHome();
	}
};
FS.extractResponse = function(response){
    if (response.data.data) {
        return response.data.data;
    }
    else {
        return null;
    }
};

FS.renderActivity = function(activity){
    if (activity.actor == FS.owner.person.getId()) {
        activity.actorName = FS.pref.getMsg("self");
    }
    if (activity.target == FS.owner.person.getId()) {
        activity.targetName = FS.pref.getMsg("self.passive");
    } 
    var raw = FS.pref.getMsg("FS.Activity." + activity.command);
    return raw.process(activity);
};

FS.renderMessage = function(message){
    var raw = FS.pref.getMsg("FS.Message." + message.messageId);
    if (message.params) {
        return raw.process(message.params);
    }
    else {
        return raw;
    }
};

FS.renderOption = function(option){
	var raw = FS.pref.getMsg("FS.Option." + option);
	return raw;
};

FS.newActivityFromResponse= function(response){
	var message = FS.extractResponse(response);
    FS.newActivity(FS.viewer.data.name + " " + FS.renderMessage(message));
};
FS.newActivity = function(text){
    var params = {};
    params[opensocial.Activity.Field.TITLE] = text;
    var activity = opensocial.newActivity(params);
    opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH);
};

FS.invite = function(uid,text){
var params = {};
params[opensocial.Activity.Field.TITLE] = text;
params['sendIds']=uid;
params['type']=1;
var activity = opensocial.newActivity(params);
opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH); 
};

